package com.ruix.app.ui.stratum.setting;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruix.app.R;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ActionMapper;
import com.ruix.app.mapper.ClassMenberMapper;
import com.ruix.app.mapper.ProhibitedMapper;
import com.ruix.app.model.ClassDetail;
import com.ruix.app.model.ClassMenber;
import com.ruix.app.model.Classes;
import com.ruix.app.model.Comment;
import com.ruix.app.model.Role;
import com.ruix.app.model.User;
import com.ruix.app.network.CacheObserver;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.CommonWebActivity;
import com.ruix.app.ui.adapter.ClassMenberAdapter;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.main.MainActivity;
import com.ruix.app.util.RoleUtil;
import com.ruix.app.widget.SwipeListView;
import com.ruix.app.widget.dialog.CommonDialog;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/25.
 */

public class ClassMenberActivity extends BaseActivity implements ClassMenberAdapter.MenberActionListener,AdapterView.OnItemClickListener{

    public static Intent newIntent(Context context, Classes classes, ClassDetail classDetail){
        Intent intent = new Intent(context,ClassMenberActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("classes",classes);
        bundle.putSerializable("classDetail",classDetail);
        intent.putExtras(bundle);
        return intent;
    }

    private Classes currentClasses;
    private ClassDetail classDetail;
    private ClassMenberAdapter adapter;
    private SwipeListView listView;
    private TextView menberCountView,noMenberView;
    private Button exitButton;

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_class_menber;
    }

    @Override
    protected void initView() {
        menberCountView = (TextView)findViewById(R.id.tv_menber_count);
        noMenberView = (TextView)findViewById(R.id.tv_no_data_tip);
        exitButton = (Button) findViewById(R.id.btn_exit_circle);
        noMenberView.setVisibility(View.GONE);

        listView = (SwipeListView) findViewById(R.id.menber_list_view);
        String role = UserManager.getCurrentUser().getRole();
        if (RoleUtil.isAdviserOrHelperOrTeacher(role)){ //班主任 小助手有禁言权限
            listView.setIsSupportSlide(true);
        } else {
            listView.setIsSupportSlide(false);
        }


        adapter = new ClassMenberAdapter(this);
        listView.setAdapter(adapter);

//        if (studentFrient){
//            View  quitCircleView =  LayoutInflater.from(this).inflate(R.layout.layout_quit_circle_footer,null);
//            quitCircleView.findViewById(R.id.btn_quit_circle).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    showQuitCircleDialog();
//                }
//            });
//            listView.addFooterView(quitCircleView);
//        }
    }

    private void updateView(ArrayList<ClassMenber> value){
        setMenberCountView(value.size());
        adapter.replaceAll(value);
    }

    private void showExitCircleView(){
        if (classDetail != null && classDetail.isTeacherFriendCircle()){
            float marginBotton =  getResources().getDimension(R.dimen.h_w_60);
            RelativeLayout.LayoutParams layoutParams =  (RelativeLayout.LayoutParams)listView.getLayoutParams();
            layoutParams.setMargins(0,0,0,(int) marginBotton);
            listView.setLayoutParams(layoutParams);
            exitButton.setVisibility(View.VISIBLE);

        }
    }

    private void setMenberCountView(int count){
        if (count > 0){
            String countString =  String.format("全部成员 （%d人）",count); //
            menberCountView.setText(countString);
            menberCountView.setVisibility(View.VISIBLE);
            noMenberView.setVisibility(View.GONE);
        } else {
            noMenberView.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void initLocalData() {
        Intent intent = getIntent();
        if (intent != null){
            currentClasses =  (Classes)intent.getSerializableExtra("classes");
            classDetail  =  (ClassDetail)intent.getSerializableExtra("classDetail");
        }

        if (classDetail != null){
            adapter.setTeacherCircle(classDetail.isTeacherFriendCircle());
        }


        showExitCircleView();
        loadClassMenberWithCache();
        loadClassMenber();

        if (currentClasses != null && currentClasses.isTeacherFriendCircle()){
            setTitle("圈子成员");
        } else {
            setTitle("班级成员");
        }

    }

    private void loadClassMenber(){
        if (currentClasses == null){
            return;
        }
        showLoading();
        RequestFactory.getClassMenbers(currentClasses.getID(), new ClassMenberMapper(), new RXObserver<ArrayList<ClassMenber>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<ClassMenber> value) {
                if (value != null) {
                    updateView(value);
                    CacheFactory.cacheClassMenberList(currentClasses.getID(),value);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });
    }

    @Override
    protected void initListener() {
        adapter.setListener(this);
        listView.setOnItemClickListener(this);
        exitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showQuitCircleDialog();
            }
        });
    }

    private void sendMsgDisable(final ClassMenber menber){
        if (currentClasses == null){
            return;
        }
        showLoading();
        RequestFactory.prohibite(currentClasses.getID(),menber.getId() ,new ProhibitedMapper(), new RXObserver<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean value) {
                menber.setDisableSendMsg(value);
                adapter.notifyDataSetHasChanged();
                if (value){
                    showSuccessTip("已禁言");
                } else {
                    showSuccessTip("禁言已解除");
                }

            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();

            }
        });
    }


    @Override
    public void negativieDiable(ClassMenber menber) {
        listView.resetItems();
        sendMsgDisable(menber);
    }

    @Override
    public void positivieRelieve(ClassMenber menber) {
        listView.resetItems();
        sendMsgDisable(menber);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(listView.isShown()){
            listView.resetItems();
        }
    }



    public void loadClassMenberWithCache(){
        if (currentClasses != null){
            CacheFactory.loadClassMenberList(currentClasses.getID(), new CacheObserver<ArrayList<ClassMenber>>() {
                @Override
                public void onNext(ArrayList<ClassMenber> value) {
                    updateView(value);
                }
            });
        }

    }

    private void showQuitCircleDialog(){
        User user = UserManager.getCurrentUser();
        if (!RoleUtil.isStudent(user.getRole())) {
            showErrorTip("角色不允许退出");
            return;
        }
        CommonDialog dialog = new CommonDialog(this);
        dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
            @Override
            public void positiveAction() {
                quitCircle();
            }

            @Override
            public void negertivieAction() {

            }
        });
        dialog.show("您退出圈子后无法再学习圈子内容了哦");
        dialog.setPositiveString("确定退出");
        dialog.seCancelString("在想想");
    }

    //退出师友圈
    private void quitCircle(){
        showLoading();
        RequestFactory.quitCircle(currentClasses.getID(), null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                //退出师友圈
                sendQuitCircle();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });
    }



    private void sendQuitCircle(){
        Intent intent = new Intent(ClassMenberActivity.this,MainActivity.class);
        startActivity(intent);

//        Intent intent = new Intent();
//        intent.setAction(RuiXConstant.NOTICE_QUIT_CIRCLE);//RuiXConstant.NOTICE_CHANGE_SHARE_STATE
//        sendOrderedBroadcast(intent,null);
//        finish();
    }


}
